﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using projectManagementWeb.Models;
using projectManagementWeb.Models.Manager;
using System.Data.Linq;
using System.Web.Security;
using System.Collections;
using System.Web.Helpers;

namespace projectManagementWeb.Controllers
{
    public class ManagerController : Controller
    {

        private projectmanagementDBDataContext _dbContext;

        public ManagerController()
        {
            Init();
        }

        private void Init()
        {
            _dbContext = new projectmanagementDBDataContext();
        }
        //
        // GET: /Manager/

        public ActionResult Index()
        {

            
            return View();
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult loadResourcesByProjectID(string id)
        {
            try
            {
                var resourceData = _dbContext.spGetAssignedResourcesByProjectID(Convert.ToInt32(id)).Select(m => new SelectListItem()
                {
                    Value = m.id.ToString(),
                    Text = m.FirstName + " " + m.LastName

                });
                return Json(resourceData, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                spGetAssignedResourcesByProjectIDResult resourceData = new spGetAssignedResourcesByProjectIDResult();
                return Json(resourceData, JsonRequestBehavior.AllowGet);
            }

        }

        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult loadModulesByProjectID(string id)
        {
            try
            {
                var moduleData = _dbContext.spGetModuleByProjectID(Convert.ToInt32(id)).Select(m => new SelectListItem()
                {
                    Value = m.ID.ToString(),
                    Text = m.name.ToString()

                });
                return Json(moduleData, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                spGetModuleByProjectIDResult moduleData = new spGetModuleByProjectIDResult();
                return Json(moduleData, JsonRequestBehavior.AllowGet);
            }

        }


        public ActionResult ManagerReportForm()
        {
            ViewBag.isProjectListEmpty = true;

            int userId = _dbContext.spGetUser(User.Identity.Name).First().id;
            if (Roles.IsUserInRole("Administrador del Sistema"))
            {
                var projectList = _dbContext.spGetAllProjects().ToList();
                ViewBag.projectList = projectList;
                if (projectList.Count > 0)
                {
                    ViewBag.isProjectListEmpty = false;
                }
            }
            else
            {
                var projectList = _dbContext.spGetProjectsBySponsorID(userId).ToList(); //todo change to byProjectLeader
                ViewBag.projectList = projectList;
                if (projectList.Count > 0)
                {
                    ViewBag.isProjectListEmpty = false;
                }
            }

            //getProjectsByID();
            return View();
        }


        [HttpPost]
        public ActionResult Index2()
        {

            return View();
        }


        [HttpPost]
        public ActionResult ManagerReportForm(ManagerReportFormModel model)
        {
            if (ModelState.IsValid)
            {
                if (model.reportType.Equals("ValorGanado"))
                {
                    return RedirectToAction("EVChart", model);
                }
                else if (model.reportType.Equals("Tareas"))
                {
                    return RedirectToAction("TaskProgressChart", model);
                }
            }

            return RedirectToAction("Index", model);
        }











        public ActionResult createProject()
        {
            /*IEnumerable<SelectListItem> projectLeaderID = _dbContext.spGetAvailableProjectLeaders()
            .Select(i => new SelectListItem
            {
                Value = i.id.ToString(),
                Text = i.UserName.ToString()
            });
            ViewBag.projectLeaderID = projectLeaderID;

            IEnumerable<SelectListItem> sponsorID = _dbContext.spGetManagers()
            .Select(i => new SelectListItem
            {
                Value = i.id.ToString(),
                Text = i.UserName.ToString()
            });
            ViewBag.sponsorID = sponsorID;

            IEnumerable<SelectListItem> statusID = _dbContext.spGetStatusTypes()
           .Select(i => new SelectListItem
           {
               Value = i.ID.ToString(),
               Text = i.name.ToString()
           });
            ViewBag.statusID = statusID;
           */

            createProjectModel model = new createProjectModel();
            model.startDate = DateTime.Now;
            model.endDate = DateTime.Now;
            return View(model);
        }
        [HttpPost]
        public ActionResult createProject(createProjectModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                projectmanagementDBDataContext pmwDB = new projectmanagementDBDataContext();
                int createStatus = pmwDB.spCreateProject(model.Name, model.Description, model.startDate, model.endDate,model.projectLeaderID, model.sponsorID, model.statusID);
                //int createStatus = pmwDB.spCrearNuevoUsuario(model.UserName, model.Password, model.FirstName, model.LastName, model.Email);

                if (createStatus == 1)
                {
                    return RedirectToAction("Index", "Manager");
                }
                else
                {
                    ModelState.AddModelError("", "An errror Ocurred while creating the project.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        public bool testFunction()
        {
            //@HttpContext.Request.Form["Button1"].ToString 
            return true;
        }
        private void getProjectsByID()
        {
            int userId = _dbContext.spGetUser(User.Identity.Name).First().id;

            List<string> proyectos = new List<string>();
            ISingleResult<spGetProjectsBySponsorIDResult> projectList = _dbContext.spGetProjectsBySponsorID(userId);

            ViewData["userID"] = userId;
            proyectos.Add("Todos");
            foreach (spGetProjectsBySponsorIDResult item in projectList)
            {
                proyectos.Add(item.name);

            }
            
            ViewBag.proyectos = proyectos;

        }


        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult loadProjectInfo(string id)
        {
            try
            {
                var data = _dbContext.spGetProjectByID(Convert.ToInt32(id)).First();
                Hashtable h = new Hashtable();
                h.Add("ID", data.ID.ToString());
                h.Add("description", data.description);
                h.Add("name", data.name);
                h.Add("startDate", data.startDate.ToString());
                h.Add("endDate", data.endDate.ToString());
                h.Add("projectLeaderID", data.projectLeaderID);
                h.Add("sponsorID", data.sponsorID);
                h.Add("statusID", data.statusID);

                return Json(h, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                spGetModuleByIDResult moduleData = new spGetModuleByIDResult();
                return Json(moduleData, JsonRequestBehavior.AllowGet);
            }
        }
        public ActionResult deleteProject()
        {
            deleteProjectModel model = new deleteProjectModel();
            model.userID = _dbContext.spGetUser(User.Identity.Name).First().id;
            return View(model);
        }
        [HttpPost]
        public ActionResult deleteProject(deleteProjectModel model)
        {
            if (ModelState.IsValid)
            {
                int userId = _dbContext.spGetUser(User.Identity.Name).First().id;
                // Attempt to register the user
                projectmanagementDBDataContext pmwDB = new projectmanagementDBDataContext();
                int resultStatus = pmwDB.spDeleteProjectModuleAndTasks(model.ID);
                if (resultStatus == 1)
                {
                    return RedirectToAction("Index", "Manager");
                }
                else
                {
                    ModelState.AddModelError("", "Un errro ocurrio al eliminar el proyecto.");
                }
            }
            // If we got this far, something failed, redisplay form
            return View(model);
        }
        public ActionResult modifyProject()
        {
            
            /*int userId = _dbContext.spGetUser(User.Identity.Name).First().id;
            var projectList = _dbContext.spGetAllProjects().ToList();
            ViewBag.projectList = projectList;

            IEnumerable<SelectListItem> projectLeaderID = _dbContext.spGetAvailableProyectLeaders()
            .Select(i => new SelectListItem
            {
                Value = i.id.ToString(),
                Text = i.UserName.ToString()
            });
            ViewBag.projectLeaderID = projectLeaderID;

            IEnumerable<SelectListItem> sponsorID = _dbContext.spGetManagers()
            .Select(i => new SelectListItem
            {
                Value = i.id.ToString(),
                Text = i.UserName.ToString()
            });
            ViewBag.sponsorID = sponsorID;

            IEnumerable<SelectListItem> statusID = _dbContext.spGetStatusTypes()
           .Select(i => new SelectListItem
           {
               Value = i.ID.ToString(),
               Text = i.name.ToString()
           });
            ViewBag.statusID = statusID;

            return View();
            */

            modifyProjectModel model = new modifyProjectModel();
            model.userID = _dbContext.spGetUser(User.Identity.Name).First().id;
            model.startDate = DateTime.Now;
            model.endDate = DateTime.Now;
            
            return View(model);
        }
        [HttpPost]
        public ActionResult modifyProject(modifyProjectModel model)
        {
            if (ModelState.IsValid)
            {
                int userId = _dbContext.spGetUser(User.Identity.Name).First().id;
                // Attempt to register the user
                projectmanagementDBDataContext pmwDB = new projectmanagementDBDataContext();
                int resultStatus = pmwDB.spUpdateProject(model.ID, model.Name, model.Description, model.startDate, model.endDate,model.projectLeaderID, model.sponsorID, model.statusID);
                if (resultStatus == 1)
                {
                    return RedirectToAction("Index", "Manager");
                }
                else
                {
                    ModelState.AddModelError("", "Un errro ocurrio al modificar el modulo.");
                }
            }
            // If we got this far, something failed, redisplay form
            return View(model);
        }

        public List<TaskDescriptionModel> GetTasks(ManagerReportFormModel model)
        {
            List<TaskDescriptionModel> tasksResult = new List<TaskDescriptionModel>();
            ISingleResult<spTasksInProgressDevResult> developerTasks;
            ISingleResult<spTasksInProgressModResult> moduleTasks;
            ISingleResult<spTasksInProgressProjectResult> projectTasks;

            if (model.moduleID == 0 && model.resourceID == 0)
            {
                projectTasks = _dbContext.spTasksInProgressProject(model.projectID);

                foreach (spTasksInProgressProjectResult task in projectTasks)
                {
                    TaskDescriptionModel realTask = new TaskDescriptionModel();
                    realTask.TaskID = task.ID;
                    realTask.TaskName = task.name;
                    realTask.StartDate = task.startDate;
                    realTask.EndDate = task.endDate;
                    realTask.PlannedEstimate = (int)task.taskEffortPlanned;
                    realTask.CurrentEffortDone = (int)task.taskRealEffort;
                    realTask.CurrentEffortPending = (int)task.taskEffortPending;
                    realTask.CurrentStatus = (int)task.tStatusID;

                    //Get the module for the Task
                    ISingleResult<spGetTaskModuleResult> moduleResult = _dbContext.spGetTaskModule(task.ID);
                    foreach (spGetTaskModuleResult module in moduleResult)
                    {
                        realTask.ModuleName = module.name;
                        realTask.ModuleID = module.ID;
                    }

                    tasksResult.Add(realTask);

                }
            }
            else if (model.moduleID != 0)
            {
                moduleTasks = _dbContext.spTasksInProgressMod(model.moduleID, model.projectID);

                foreach (spTasksInProgressModResult task in moduleTasks)
                {
                    TaskDescriptionModel realTask = new TaskDescriptionModel();
                    realTask.TaskID = task.ID;
                    realTask.TaskName = task.name;
                    realTask.StartDate = task.startDate;
                    realTask.EndDate = task.endDate;
                    realTask.PlannedEstimate = (int)task.taskEffortPlanned;
                    realTask.CurrentEffortDone = (int)task.taskRealEffort;
                    realTask.CurrentEffortPending = (int)task.taskEffortPending;
                    realTask.CurrentStatus = (int)task.tStatusID;

                    //Get the module for the Task
                    ISingleResult<spGetTaskModuleResult> moduleResult = _dbContext.spGetTaskModule(task.ID);
                    foreach (spGetTaskModuleResult module in moduleResult)
                    {
                        realTask.ModuleName = module.name;
                        realTask.ModuleID = module.ID;
                    }

                    tasksResult.Add(realTask);

                }
            }
            else if (model.resourceID != 0)
            {
                developerTasks = _dbContext.spTasksInProgressDev(model.resourceID, model.projectID);

                foreach (spTasksInProgressDevResult task in developerTasks)
                {
                    TaskDescriptionModel realTask = new TaskDescriptionModel();
                    realTask.TaskID = task.ID;
                    realTask.TaskName = task.name;
                    realTask.StartDate = task.startDate;
                    realTask.EndDate = task.endDate;
                    realTask.PlannedEstimate = (int)task.taskEffortPlanned;
                    realTask.CurrentEffortDone = (int)task.taskRealEffort;
                    realTask.CurrentEffortPending = (int)task.taskEffortPending;
                    realTask.CurrentStatus = (int)task.tStatusID;

                    //Get the module for the Task
                    ISingleResult<spGetTaskModuleResult> moduleResult = _dbContext.spGetTaskModule(task.ID);
                    foreach (spGetTaskModuleResult module in moduleResult)
                    {
                        realTask.ModuleName = module.name;
                        realTask.ModuleID = module.ID;
                    }

                    tasksResult.Add(realTask);

                }

            }

            return tasksResult;
        }


        public ActionResult TaskProgressChart(ManagerReportFormModel model)
        {
            if (ModelState.IsValid)
            {
                DateTime today = DateTime.Today;
                DateTime startDate = DateTime.Today;
                List<string> id = new List<string>();
                List<int> ee = new List<int>();
                List<int> er = new List<int>();
                List<int> ef = new List<int>();
                String[] xLabel = { " ", "Total de tareas" };
                int[] eeTot = new int[2] { 0, 0 };
                int[] erTot = new int[2] { 0, 0 };
                int[] efTot = new int[2] { 0, 0 };
                int index = 1;
                float width_chart = 0;
                ViewBag.ValidDate = "true";


                ISingleResult<spTasksInProgressDevResult> developerTasks;// = _dbContext.sp
                ISingleResult<spTasksInProgressProjectResult> projectTasks;
                ISingleResult<spTasksInProgressModResult> moduleTasks;

                if (model.moduleID == 0 && model.resourceID == 0) // report by project
                {
                    try {
                        startDate = (DateTime)_dbContext.spGetProjectStartDate(model.projectID).First().startDate;
                        ViewBag.project = 1;
                    }
                    catch (Exception)
                    {
                        ViewBag.project = 0;
                        return View();
                    }
                   
                }
                else if (model.moduleID != 0)  // report by module
                {
                    try
                    {
                        startDate = (DateTime)_dbContext.spGetModuleStartDate(model.moduleID).First().startDate;
                        ViewBag.project = 1;
                    }
                    catch (Exception)
                    {
                        ViewBag.project = 0;
                        return View();
                    }
                    

                }
                else if (model.resourceID != 0)  // report by developer
                {
                    try
                    {
                        startDate = (DateTime)_dbContext.spGetProjectStartDate(model.projectID).First().startDate;
                        ViewBag.project = 1;
                    }
                    catch (Exception)
                    {
                        ViewBag.project = 0;
                        return View();
                    }
                   
                }

                TaskListModel taskList = new TaskListModel();
                taskList.taskList = this.GetTasks(model);

                if (startDate.Date > today.Date)
                {
                    ViewBag.ValidDate = "false";
                    ViewBag.startDate = startDate;
                    return View();
                }

                if (model.moduleID == 0 && model.resourceID == 0)
                {
                    projectTasks = _dbContext.spTasksInProgressProject(model.projectID);

                    foreach (spTasksInProgressProjectResult progressTask in projectTasks)
                    {
                        id.Add(" ");
                        id.Add("#" + index.ToString());
                        index = index + 1;
                        //id.Add(" " + progressTask.ID);                    

                        ee.Add((int)progressTask.taskEffortPlanned);
                        ee.Add(0);

                        er.Add(0);
                        er.Add((int)progressTask.taskRealEffort);

                        ef.Add(0);
                        ef.Add((int)progressTask.taskEffortPending);

                        eeTot[0] = eeTot[0] + (int)progressTask.taskEffortPlanned;
                        erTot[1] = erTot[1] + (int)progressTask.taskRealEffort;
                        efTot[1] = efTot[1] + (int)progressTask.taskEffortPending;
                    }

                }
                else if (model.moduleID != 0)
                {
                    moduleTasks = _dbContext.spTasksInProgressMod(model.moduleID, model.projectID);

                    foreach (spTasksInProgressModResult progressTask in moduleTasks)
                    {
                        id.Add(" ");
                        id.Add("#" + index.ToString());
                        index = index + 1;
                        //id.Add(" " + progressTask.ID);                    

                        ee.Add((int)progressTask.taskEffortPlanned);
                        ee.Add(0);

                        er.Add(0);
                        er.Add((int)progressTask.taskRealEffort);

                        ef.Add(0);
                        ef.Add((int)progressTask.taskEffortPending);

                        eeTot[0] = eeTot[0] + (int)progressTask.taskEffortPlanned;
                        erTot[1] = erTot[1] + (int)progressTask.taskRealEffort;
                        efTot[1] = efTot[1] + (int)progressTask.taskEffortPending;
                    }


                }
                else if (model.resourceID != 0)
                {
                    developerTasks = _dbContext.spTasksInProgressDev(model.resourceID, model.projectID);

                    foreach (spTasksInProgressDevResult progressTask in developerTasks)
                    {
                        id.Add(" ");
                        id.Add("#" + index.ToString());
                        index = index + 1;
                        //id.Add(" " + progressTask.ID);                    

                        ee.Add((int)progressTask.taskEffortPlanned);
                        ee.Add(0);

                        er.Add(0);
                        er.Add((int)progressTask.taskRealEffort);

                        ef.Add(0);
                        ef.Add((int)progressTask.taskEffortPending);

                        eeTot[0] = eeTot[0] + (int)progressTask.taskEffortPlanned;
                        erTot[1] = erTot[1] + (int)progressTask.taskRealEffort;
                        efTot[1] = efTot[1] + (int)progressTask.taskEffortPending;
                    }

                }

                if (model.detail.Equals("Individual"))
                {
                    if (id.Count == 0)
                    {
                        id.Add("0 tareas en progreso");
                        ee.Add(0);
                        er.Add(0);
                        ef.Add(0);
                    }

                    if (id.Count < 8) width_chart = 800;
                    else
                    {
                        width_chart = (float)id.Count() / 8;
                        width_chart = width_chart * 800;
                    }

                    var chart = new Chart(width: (int)width_chart, height: 600, theme: ChartTheme.Blue)
                        .AddTitle("Tareas en progreso individuales")
                        .AddSeries(chartType: "StackedColumn",
                        xValue: id,
                        yValues: ee,
                        name: "Esfuerzo estimado")
                        .AddSeries(chartType: "StackedColumn",
                        xValue: id,
                        yValues: er,
                        name: "Esfuerzo real")
                        .AddSeries(chartType: "StackedColumn",
                        xValue: id,
                        yValues: ef,
                        name: "Esfuerzo faltante")
                        .AddLegend()
                        .SetXAxis(title: "# de tarea")
                        .SetYAxis(title: "Tiempo (horas)")
                        //.Write();
                        .GetBytes("jpeg");
                    //return View(model);
                    //return File(chart, "image/jpeg");

                    var base64Data = Convert.ToBase64String(chart);
                    ViewBag.ImageData = base64Data;
                    ViewBag.ImageContentType = "image/jpeg";

                    return View(taskList);
                }
                else if (model.detail.Equals("Total"))
                {
                    if (id.Count == 0)
                    {
                        xLabel[0] = " ";
                        xLabel[1] = "0 tareas en progreso";
                    }
                    var chart = new Chart(width: 800, height: 600, theme: ChartTheme.Blue)
                         .AddTitle("Total de tareas en progreso")
                         .AddSeries(chartType: "StackedColumn",
                         xValue: xLabel,
                         yValues: eeTot,
                         name: "Esfuerzo estimado total")
                         .AddSeries(chartType: "StackedColumn",
                         xValue: xLabel,
                         yValues: erTot,
                         name: "Esfuerzo real total")
                         .AddSeries(chartType: "StackedColumn",
                         xValue: xLabel,
                         yValues: efTot,
                         name: "Esfuerzo faltante total")
                         .AddLegend()
                         .SetXAxis(title: "Tareas")
                         .SetYAxis(title: "Tiempo (horas)")
                        //.Write();
                         .GetBytes("jpeg");

                    //return View(model);
                    //return File(chart, "image/png");

                    var base64Data = Convert.ToBase64String(chart);
                    ViewBag.ImageData = base64Data;
                    ViewBag.ImageContentType = "image/jpeg";

                    return View(taskList);

                }

            }
            return View(model);
        }


        public ActionResult EVChart(ManagerReportFormModel model)
        {
            if (ModelState.IsValid)
            {
                DateTime today = DateTime.Today;
                DateTime startDate = DateTime.Today;
                DateTime endDate = DateTime.Today;
                DateTime startDateBL = DateTime.Today;
                DateTime endDateBL = DateTime.Today;
                DateTime stopDate;
                DateTime reportDate;
                int index = 1;
                int moduleID;
                int developerId;
                float width_chart = 0;
                TimeSpan tempSize;
                int size;
                ViewBag.ValidDate = "true";
                ISingleResult<spEVmoduloResult> moduleTasks = null;
                ISingleResult<spEVdevResult> developerTasks = null;
                ISingleResult<spEVprojectResult> projectTasks = null;
                ISingleResult<spEVmoduloResult> moduleTasks2 = null;
                ISingleResult<spEVdevResult> developerTasks2 = null;
                ISingleResult<spEVprojectResult> projectTasks2 = null;

                ISingleResult<spModuleBaseLineResult> moduleTasksBL = null;
                ISingleResult<spdevBaseLineResult> developerTasksBL = null;
                ISingleResult<spBaseLineResult> projectTasksBL = null;
                ISingleResult<spModuleBaseLineResult> moduleTasksBL2 = null;
                ISingleResult<spdevBaseLineResult> developerTasksBL2 = null;
                ISingleResult<spBaseLineResult> projectTasksBL2 = null;

                String tipoChart = "";
                if (model.moduleID == 0 && model.resourceID == 0) // report by project
                {
                    try
                    {
                        startDate = (DateTime)_dbContext.spGetProjectStartDate(model.projectID).First().startDate;
                        endDate = (DateTime)_dbContext.spGetProjectStartDate(model.projectID).First().endDate;
                        ViewBag.project = 1;
                    }
                    catch (Exception)
                    {
                        ViewBag.project = 0;
                        return View();
                    }

                    projectTasks = _dbContext.spEVproject(model.projectID);
                    projectTasks2 = _dbContext.spEVproject(model.projectID);
                    projectTasksBL = _dbContext.spBaseLine(model.projectID);
                    projectTasksBL2 = _dbContext.spBaseLine(model.projectID);
                    reportDate = startDate;
                    tipoChart = "Del Proyecto " + model.projectID;
                }
                else if (model.moduleID != 0)  // report by module
                {
                    moduleID = model.moduleID;
                    // create a sp to get the start date for module
                    try
                    {
                        startDate = (DateTime)_dbContext.spGetModuleStartDate(model.moduleID).First().startDate;
                        endDate = (DateTime)_dbContext.spGetModuleStartDate(model.moduleID).First().endDate;
                        ViewBag.project = 1;
                    }
                    catch (Exception)
                    {
                        ViewBag.project = 0;
                        return View();
                    }

                    moduleTasks = _dbContext.spEVmodulo(model.moduleID, model.projectID);
                    moduleTasks2 = _dbContext.spEVmodulo(model.moduleID, model.projectID);
                    moduleTasksBL = _dbContext.spModuleBaseLine(model.moduleID, model.projectID);
                    moduleTasksBL2 = _dbContext.spModuleBaseLine(model.moduleID, model.projectID);
                    reportDate = startDate;
                    tipoChart = "Del modulo " + moduleID;
                }
                else if (model.resourceID != 0)  // report by developer
                {
                    developerId = model.resourceID;
                    try
                    {
                        startDate = (DateTime)_dbContext.spGetProjectStartDate(model.projectID).First().startDate;
                        endDate = (DateTime)_dbContext.spGetProjectStartDate(model.projectID).First().endDate;
                    }
                    catch (Exception)
                    {
                        ViewBag.project = 0;
                        return View();
                    }

                    developerTasks = _dbContext.spEVdev(model.resourceID, model.projectID);
                    developerTasks2 = _dbContext.spEVdev(model.resourceID, model.projectID);
                    developerTasksBL = _dbContext.spdevBaseLine(model.resourceID, model.projectID);
                    developerTasksBL2 = _dbContext.spdevBaseLine(model.resourceID, model.projectID);
                    reportDate = startDate;
                    tipoChart = "Del desarrollador " + developerId;
                }

                ViewBag.fechaFin = endDate;
                if (model.moduleID == 0 && model.resourceID == 0)
                {
                    foreach (spEVprojectResult projectTask2 in projectTasks2)
                    {
                        if (projectTask2.tStatusID == 16 || projectTask2.tStatusID == 20)
                        {
                            if (projectTask2.realEndDate > endDate)
                            {
                                endDate = (DateTime)projectTask2.realEndDate;
                            }
                        }

                    }

                    foreach (spBaseLineResult projectTaskBL2 in projectTasksBL2)
                    {
                        if (projectTaskBL2.endDateBaseLine > endDate)
                        {
                            endDate = (DateTime)projectTaskBL2.endDateBaseLine;
                        }
                        if (projectTaskBL2.startDateBaseLine < startDate)
                        {
                            startDate = (DateTime)projectTaskBL2.startDateBaseLine;
                        }

                    }
                }
                else if (model.moduleID != 0)
                {
                    foreach (spEVmoduloResult modTask2 in moduleTasks2)
                    {
                        if (modTask2.tStatusID == 16 || modTask2.tStatusID == 20)
                        {
                            if (modTask2.realEndDate > endDate)
                            {
                                endDate = (DateTime)modTask2.realEndDate;
                            }
                        }

                    }

                    foreach (spModuleBaseLineResult moduleTaskBL2 in moduleTasksBL2)
                    {
                        if (moduleTaskBL2.endDateBaseLine > endDate)
                        {
                            endDate = (DateTime)moduleTaskBL2.endDateBaseLine;
                        }
                        if (moduleTaskBL2.startDateBaseLine < startDate)
                        {
                            startDate = (DateTime)moduleTaskBL2.startDateBaseLine;
                        }

                    }
                }
                else if (model.resourceID != 0)
                {
                    foreach (spEVdevResult devTask2 in developerTasks2)
                    {
                        if (devTask2.tStatusID == 16 || devTask2.tStatusID == 20)
                        {
                            if (devTask2.realEndDate > endDate)
                            {
                                endDate = (DateTime)devTask2.realEndDate;
                            }
                        }

                    }

                    foreach (spdevBaseLineResult devTaskBL2 in developerTasksBL2)
                    {
                        if (devTaskBL2.endDateBaseLine > endDate)
                        {
                            endDate = (DateTime)devTaskBL2.endDateBaseLine;
                        }
                        if (devTaskBL2.startDateBaseLine < startDate)
                        {
                            startDate = (DateTime)devTaskBL2.startDateBaseLine;
                        }

                    }
                }


                if (startDate.Date > today.Date)
                {
                    ViewBag.ValidDate = "false";
                    ViewBag.startDate = startDate;
                    return View();
                }

                if (endDate.Date >= today.Date)
                {
                    tempSize = today.Subtract(startDate);
                    stopDate = today;
                }
                else
                {
                    tempSize = endDate.Subtract(startDate);
                    stopDate = endDate;
                }

                if ((tempSize.Days % 7) == 0)
                {
                    size = ((tempSize.Days) / 7) + 1;
                }
                else
                {
                    size = ((tempSize.Days) / 7) + 2;
                }

                float[] estadisticas = new float[5];

                float[] pv = new float[size];
                float[] ev = new float[size];
                float[] ac = new float[size];
                float[] bl = new float[size];
                float[] pvP = new float[size];
                float[] evP = new float[size];
                float[] acP = new float[size];
                float[] blP = new float[size];
                DateTime[] fechas = new DateTime[size];
                String[] fechas2 = new String[size];
                fechas[0] = startDate.Date;
                for (int i = 1; i < size; i++)
                {
                    if (fechas[i - 1].AddDays(7).Date < stopDate.Date)
                    {
                        fechas[i] = fechas[i - 1].AddDays(7).Date;
                    }
                    else
                    {
                        fechas[i] = stopDate.Date;
                    }
                }

                for (int i = 0; i < size; i++)
                {
                    pv[i] = 0;
                    ev[i] = 0;
                    ac[i] = 0;
                    bl[i] = 0;
                    pvP[i] = 0;
                    evP[i] = 0;
                    acP[i] = 0;
                    blP[i] = 0;
                }

                float eac = 0;

                if (model.moduleID == 0 && model.resourceID == 0)
                {
                    foreach (spEVprojectResult projectTask in projectTasks)
                    {
                        reportDate = startDate;
                        reportDate = reportDate.AddDays(7);
                        eac = eac + (float)projectTask.taskEffortPlanned;

                        if (projectTask.tStatusID != 17)
                        {

                            if (projectTask.endDate.Date <= stopDate.Date)
                            {
                                while (projectTask.endDate.Date > reportDate.Date)
                                {
                                    reportDate = reportDate.AddDays(7);
                                    index = index + 1;
                                }
                                pv[index] = pv[index] + (float)projectTask.taskEffortPlanned;
                            }

                        }

                        index = 1;

                        if (projectTask.tStatusID == 16 || projectTask.tStatusID == 20)
                        {
                            reportDate = startDate;
                            reportDate = reportDate.AddDays(7);

                            if (projectTask.realEndDate.Value.Date <= stopDate.Date)
                            {
                                while (projectTask.realEndDate.Value.Date > reportDate.Date)
                                {
                                    reportDate = reportDate.AddDays(7);
                                    index = index + 1;
                                }
                                ev[index] = ev[index] + (float)projectTask.taskEffortPlanned;
                                ac[index] = ac[index] + (float)projectTask.taskRealEffort;
                            }

                        }
                        index = 1;

                    }


                    foreach (spBaseLineResult projectTaskBL in projectTasksBL)
                    {
                        reportDate = startDate;
                        reportDate = reportDate.AddDays(7);

                        if (projectTaskBL.endDateBaseLine.Value.Date <= stopDate.Date)
                        {
                            while (projectTaskBL.endDateBaseLine.Value.Date > reportDate.Date)
                            {
                                reportDate = reportDate.AddDays(7);
                                index = index + 1;
                            }
                            bl[index] = bl[index] + (float)projectTaskBL.taskEffortBaseLine;
                        }

                        index = 1;
                    }

                }
                else if (model.moduleID != 0)
                {
                    foreach (spEVmoduloResult modTask in moduleTasks)
                    {
                        reportDate = startDate;
                        reportDate = reportDate.AddDays(7);
                        eac = eac + (float)modTask.taskEffortPlanned;

                        if (modTask.tStatusID != 17)
                        {
                            if (modTask.endDate.Date <= stopDate.Date)
                            {
                                while (modTask.endDate.Date > reportDate.Date)
                                {
                                    reportDate = reportDate.AddDays(7);
                                    index = index + 1;
                                }
                                pv[index] = pv[index] + (float)modTask.taskEffortPlanned;
                            }

                        }


                        index = 1;

                        if (modTask.tStatusID == 16 || modTask.tStatusID == 20)
                        {
                            reportDate = startDate;
                            reportDate = reportDate.AddDays(7);
                            if (modTask.realEndDate.Value.Date <= stopDate.Date)
                            {
                                while (modTask.realEndDate.Value > reportDate.Date)
                                {
                                    reportDate = reportDate.AddDays(7);
                                    index = index + 1;
                                }
                                ev[index] = ev[index] + (float)modTask.taskEffortPlanned;
                                ac[index] = ac[index] + (float)modTask.taskRealEffort;
                            }



                        }
                        index = 1;

                    }

                    foreach (spModuleBaseLineResult moduleTaskBL in moduleTasksBL)
                    {
                        reportDate = startDate;
                        reportDate = reportDate.AddDays(7);

                        if (moduleTaskBL.endDateBaseLine.Value.Date <= stopDate.Date)
                        {
                            while (moduleTaskBL.endDateBaseLine.Value.Date > reportDate.Date)
                            {
                                reportDate = reportDate.AddDays(7);
                                index = index + 1;
                            }
                            bl[index] = bl[index] + (float)moduleTaskBL.taskEffortBaseLine;
                        }

                        index = 1;
                    }
                }
                else if (model.resourceID != 0)
                {
                    foreach (spEVdevResult devTask in developerTasks)
                    {
                        reportDate = startDate;
                        reportDate = reportDate.AddDays(7);
                        eac = eac + (float)devTask.taskEffortPlanned;

                        if (devTask.tStatusID != 17)
                        {
                            if (devTask.endDate.Date <= stopDate.Date)
                            {
                                while (devTask.endDate.Date > reportDate.Date)
                                {
                                    reportDate = reportDate.AddDays(7);
                                    index = index + 1;
                                }
                                pv[index] = pv[index] + (float)devTask.taskEffortPlanned;
                            }

                        }

                        index = 1;

                        if (devTask.tStatusID == 16 || devTask.tStatusID == 20)
                        {
                            reportDate = startDate;
                            reportDate = reportDate.AddDays(7);

                            if (devTask.realEndDate.Value.Date <= stopDate.Date)
                            {
                                while (devTask.realEndDate.Value.Date > reportDate.Date)
                                {
                                    reportDate = reportDate.AddDays(7);
                                    index = index + 1;
                                }
                                ev[index] = ev[index] + (float)devTask.taskEffortPlanned;
                                ac[index] = ac[index] + (float)devTask.taskRealEffort;
                            }



                        }
                        index = 1;

                    }

                    foreach (spdevBaseLineResult developerTaskBL in developerTasksBL)
                    {
                        reportDate = startDate;
                        reportDate = reportDate.AddDays(7);


                        if (developerTaskBL.endDateBaseLine <= stopDate)
                        {
                            while (developerTaskBL.endDateBaseLine.Value.Date > reportDate.Date)
                            {
                                reportDate = reportDate.AddDays(7);
                                index = index + 1;
                            }
                            bl[index] = bl[index] + (float)developerTaskBL.taskEffortBaseLine;
                        }

                        index = 1;

                    }
                }

                for (int i = 1; i < size; i++)
                {
                    pv[i] = pv[i] + pv[i - 1];
                    ev[i] = ev[i] + ev[i - 1];
                    ac[i] = ac[i] + ac[i - 1];
                    bl[i] = bl[i] + bl[i - 1];
                }

                if (size < 40) width_chart = 800;
                else
                {
                    width_chart = (float)size / 40;
                    width_chart = width_chart * 800;
                }

                if (model.units.Equals("Horas"))
                {
                    var chart = new Chart(width: (int)width_chart, height: 600, theme: ChartTheme.Blue)
                         .AddTitle("Valor ganado en horas de construcción")
                         .AddSeries(chartType: "Line",
                        //xValue: xLabel,
                         yValues: pv,
                         name: "Valor planeado")

                        .AddSeries(chartType: "Line",
                        // xValue: xLabel,
                         yValues: bl,
                         name: "Línea base")

                         .AddSeries(chartType: "Line",
                        //xValue: xLabel,
                         yValues: ev,
                         name: "Valor ganado")
                         .AddSeries(chartType: "Line",
                        // xValue: xLabel,
                         yValues: ac,
                         name: "Costo actual")

                         .AddLegend()
                         .SetXAxis(title: "Periodo de tiempo (semanas)")
                         .SetYAxis(title: "Avance en horas")
                        //.Write();
                          .GetBytes("jpeg");
                    //return File(chart, "image/png");

                    var base64Data = Convert.ToBase64String(chart);
                    ViewBag.ImageData = base64Data;
                    ViewBag.ImageContentType = "image/jpeg";
                    ViewBag.Symbol = "hrs.";
                    ViewBag.PV = pv;
                    ViewBag.EV = ev;
                    ViewBag.AC = ac;
                    ViewBag.BL = bl;

                }
                else if (model.units.Equals("Porcentaje"))
                {

                    if (eac != 0)
                    {
                        for (int i = 0; i < size; i++)
                        {
                            pvP[i] = (pv[i] / eac) * 100;
                            evP[i] = (ev[i] / eac) * 100;
                            acP[i] = (ac[i] / eac) * 100;
                            blP[i] = (bl[i] / eac) * 100;
                        }
                    }

                    var chart = new Chart(width: (int)width_chart, height: 600, theme: ChartTheme.Blue)
                          .AddTitle("Valor ganado en porcentaje")
                          .AddSeries(chartType: "Line",
                        // xValue: xLabel,
                          yValues: pvP,
                          name: "Valor planeado")


                          .AddSeries(chartType: "Line",
                        // xValue: xLabel,
                          yValues: blP,
                          name: "Línea base")


                          .AddSeries(chartType: "Line",
                        // xValue: xLabel,
                          yValues: evP,
                          name: "Valor ganado")
                          .AddSeries(chartType: "Line",
                        // xValue: xLabel,
                          yValues: acP,
                          name: "Costo actual")

                          .AddLegend()
                          .SetXAxis(title: "Periodo de tiempo (semanas)")
                          .SetYAxis(title: "Avance en porcentaje (%)")
                        //.Write();
                          .GetBytes("jpeg");
                    //return File(chart, "image/png");

                    var base64Data = Convert.ToBase64String(chart);
                    ViewBag.ImageData = base64Data;
                    ViewBag.ImageContentType = "image/jpeg";
                    ViewBag.Symbol = "%";
                    ViewBag.PV = pvP;
                    ViewBag.EV = evP;
                    ViewBag.AC = acP;
                    ViewBag.BL = blP;
                }

                // Calculando valores estadísticos
                estadisticas[0] = eac;
                estadisticas[1] = ev[size - 1] - ac[size - 1]; // Varianza costo
                estadisticas[2] = ev[size - 1] - pv[size - 1]; // varianza calendario
                if (ac[size - 1] == 0) estadisticas[3] = 0;
                else estadisticas[3] = ev[size - 1] / ac[size - 1]; // indice de costo
                if (pv[size - 1] == 0) estadisticas[4] = 0;
                else estadisticas[4] = ev[size - 1] / pv[size - 1]; // indice calendario

                ViewBag.fechas = fechas;
                ViewBag.size = fechas.Count();
                ViewBag.estadisticas = estadisticas;
                return View();

            }
            return RedirectToAction("Index");
        }

    }
}
